<!DOCTYPE html>
<html lang="zh" style="font-size: 26.7312px;">

</html>
<!-- 中文语言 字体大小*/ -->

<head>
  <meta charset="UTF-8">
  <!-- <link href="https://fonts.font.im/css?family=Indie+Flower" rel="stylesheet"> -->
  <title>工大版教师节专属贺卡</title>
  <!--自动适应屏幕，且不可缩放-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <!--样式表和js文件导入-->
  <link rel="prefetch stylesheet" href="../static/css/style.css?v=1.0.18" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="../static/css/weui.min.css">
  <link rel="preload" as="font" href="../static/font/kaiti7000.TTF" crossorigin="anonymous">

  <script type="text/javascript" src="../static/js/weui.min.js"></script>
  <script src="../static/js/jquery-3.4.1.min.js"></script>
  <script type="text/javascript" src="../static/js/common.js"></script>
  <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  <!--字体大小转为px-->
  <script>
    document.documentElement.style.fontSize = document.documentElement.clientWidth * 14 / 320 + 'px';
  </script>
  <script type="text/javascript">
    var winHeight = $(window).height();
    $("body").height(winHeight);
    var cardImageNum
    var cardImageUrl
    var receiverText
    var contentText
    var writerText

    // 加载时调用
    window.onload = function () {
      // 从url中取出参数
      getData();
      // 拼接得到图片地址
      cardImageUrl = "./static/img/" + cardImageNum.toString() + ".jpg"
      // 横向文本绘制相关参数
      var fontSize;
      var receiverStartX;
      var receiverStartY;
      var contentStartX;
      var contentStartY;
      var writerStartX;
      var writerStartY;
      var textMaxLength;
      // 第一张贺卡为竖向文本，只配置字体大小
      if (cardImageNum == 1) {
        fontSize = 50;
      } else if (cardImageNum == 2) {
        fontSize = 40; // 50
        receiverStartX = 20;
        receiverStartY = 700;
        contentStartX = 20;
        contentStartY = 710;
        writerStartX = 20;
        writerStartY = 970;
        textMaxLength = 630; // 650

      } else if (cardImageNum == 3) {
        fontSize = 50;
        receiverStartX = 20;
        receiverStartY = 520;
        contentStartX = 20;
        contentStartY = 540;
        writerStartX = 20;
        writerStartY = 970;
        textMaxLength = 640;

      } else if (cardImageNum == 4) {
        fontSize = 50;
        receiverStartX = 20;
        receiverStartY = 650;
        contentStartX = 20;
        contentStartY = 670;
        writerStartX = 20;
        writerStartY = 970;
        textMaxLength = 640;

      } else if (cardImageNum == 5 || cardImageNum == 6 || cardImageNum == 7) {
        fontSize = 50;
        receiverStartX = 20;
        receiverStartY = 520;
        contentStartX = 20;
        contentStartY = 540;
        writerStartX = 20;
        writerStartY = 970;
        textMaxLength = 640;

      } else if (cardImageNum == 8) {
        fontSize = 50;
        receiverStartX = 20;
        receiverStartY = 500;
        contentStartX = 20;
        contentStartY = 520;
        writerStartX = 20;
        writerStartY = 970;
        textMaxLength = 640;
      }
      var fontType = "newtext"
      var textFont = fontSize.toString() + 'px ' + fontType;
      drawCelebrateCard(fontSize, textFont, receiverStartX, receiverStartY, contentStartX, contentStartY,
        writerStartX, writerStartY, textMaxLength, (cardImageNum == 1) ? true : false)
    }

    // 用于在加载时从url中获取参数
    // 参数说明:name从url地址中获取的变量名
    function GetQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      // console.log(r) // for debug
      if (r != null)
        return decodeURI(r[2]);
      return null;
    }

    // 从url中取出参数
    // 选择的贺卡样式cardImageNum，称谓receiverText，内容contentText，书写人writerText
    function getData() {
      cardImageNum = GetQueryString("cardImageNum")
      receiverText = GetQueryString("receiverText");
      contentText = GetQueryString("contentText");
      writerText = GetQueryString("writerText");
    }

    // 根据之前选择的贺卡样式和文本生成贺卡
    // 参数说明：
    // fontSize字体大小
    // textFont字题样式
    // receiverStartX接收人文本起始x坐标
    // receiverStartY接收人文本起始y坐标
    // contentStartX祝福内容文本起始x坐标
    // contentStartY祝福内容文本起始y坐标
    // writerStartX发送人文本起始x坐标
    // writerStartY发送人文本起始y坐标
    // textMaxLength文本每行最大长度
    function drawCelebrateCard(fontSize, textFont, receiverStartX, receiverStartY, contentStartX, contentStartY,
      writerStartX, writerStartY, textMaxLength, isVertical) {
      var canvas = document.createElement("canvas");

      canvas.width = 700;
      canvas.height = 1000;
      var ctx = canvas.getContext("2d");
      ctx.rect(0, 0, canvas.width, canvas.height);

      // 绘制背景底图
      var img = new Image();
      console.log(cardImageUrl)
      img.src = cardImageUrl;
      // img.crossOrigin = "anonymous";   本地开启这个选项会导致报错
      img.onload = function () {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        ctx.font = textFont;

        if (isVertical) {
          var blank = "                                        " // 让写信人居于底部
          var str = receiverText + "\n    " + contentText + "\n" + blank + writerText;
          // str = str.replace(
          //   /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g,
          //   " ");
          drawTextVertical(ctx, str, 430, 100, 200, 750);
        } else {
          // 填入老师名
          ctx.fillText(receiverText + ":", receiverStartX, receiverStartY);
          // 调用drawText用于实现长字符串的换行
          drawTextHorizontal(fontSize, ctx, "\xa0\xa0\xa0\xa0\xa0" + contentText, contentStartX, contentStartY, textMaxLength)
          // 填入寄出人
          ctx.fillText(writerText, writerStartX, writerStartY);
        }
        // 生成图片链接
        var src = canvas.toDataURL("image/jpg", 1);
        // 展示成品
        document.getElementById("celebrateCardImage").src = src;
        sendCanvasToserver(src);
        // 将数据发送到后台
        $.ajax({
          url: "up_picture_data",
          type: "POST",
          dataType: "json",
          data: {
            'receiver': receiverText,
            'content': contentText,
            'writer': writerText,
            'cardNum': cardImageNum
          },
          success: function (res) {
            console.log("Successfully transform to server");
          },
          fail: function (error) {
            console.log("Fail in transforming to server");
            console.log(error)
          }
        })
      }
    }

    // 处理长字符串以实现分行绘制
    // 参数说明：fontSize:字体的字号
    // context:canvas.context
    // t:待输入字符串
    // x:起始横坐标
    // y:起始纵坐标
    // w:每行长度
    function drawTextHorizontal(fontSize, context, t, x, y, w) {
      var chr = t.split("");
      var temp = "";
      var row = [];
      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width < w) {
          ;
        } else {
          row.push(temp);
          temp = "";
        }
        temp += chr[a];
      }
      row.push(temp);
      for (var b = 0; b < row.length; b++) {
        context.fillText(row[b], x, y + (b + 1) * fontSize);
      }
    }

    // 本地进行base64转换为图片上传
    function b64ToUint8Array(b64Image) {
      var img = atob(b64Image.split(',')[1]);
      var img_buffer = [];
      var i = 0;
      while (i < img.length) {
        img_buffer.push(img.charCodeAt(i));
        i++;
      }
      return new Uint8Array(img_buffer);
    };

    function sendCanvasToserver(b64Image) {
      // var b64Image = canvas.toDataURL('image/png');
      var u8Image = b64ToUint8Array(b64Image);
      var formData = new FormData();
      // 包装图片文件
      formData.append("image",
        new File(
          [new Blob([u8Image], {
            type: "image/jpg"
          })],
          receiverText + "_" + writerText
        )
      );
      // 建立连接
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "./up_picture", true); 
      xhr.send(formData);
    }

    // 画竖排文本，从右到左，水平居中，可以水平溢出
    function drawTextVertical(ctx, text, x, y, width, height, hasStroke = false) {
      let [oldAlign, oldBaseLine] = [ctx.textAlign, ctx.textBaseline];
      [ctx.textAlign, ctx.textBaseline] = ['center', 'middle']
      let lineWidth = parseInt(ctx.font) // ctx.font必须以'XXpx'开头

      // 计算每个字符的尺寸信息
      let charInfo = []
      for (let char of text) {
        let cInfo = {
          char: char,
          needsRotation: needsRotation(char) // 中日韩文字不用旋转
        }
        if (cInfo.needsRotation) {
          [cInfo.width, cInfo.height] = [lineWidth, ctx.measureText(char).width]
        } else {
          [cInfo.width, cInfo.height] = [ctx.measureText(char).width, lineWidth]
        }
        charInfo.push(cInfo)
      }

      // 计算每一列
      let lineInfo = []
      let curLine = []
      let curLineHeight = 0
      for (let info of charInfo) {
        if (info.char === '\n' || curLineHeight + info.height > height) {
          lineInfo.push({
            charInfo: curLine,
            height: curLineHeight
          })
          curLine = info.char === '\n' ? [] : [info]
          curLineHeight = info.height
        } else {
          curLine.push(info)
          curLineHeight += info.height
        }
      }
      lineInfo.push({
        charInfo: curLine,
        height: curLineHeight
      })

      // 逐字画文本
      let lineX = x + (width + lineWidth * lineInfo.length) / 2 - lineWidth / 2 // 列中心的坐标
      for (let lInfo of lineInfo) {
        let charY // 字符顶端的坐标
        if (oldAlign === 'center') {
          charY = y + (height - lInfo.height) / 2
        } else if (oldAlign === 'right') { // 这里右对齐视为底端对齐，左对齐视为顶端对齐
          charY = y + height - lInfo.height
        } else {
          charY = y
        }

        // 画一列文本
        for (let cInfo of lInfo.charInfo) {
          ctx.translate(lineX, charY + cInfo.height / 2)
          if (cInfo.needsRotation) {
            ctx.rotate(90 * Math.PI / 180)
          }
          // 画一个字符
          if (hasStroke) {
            ctx.strokeText(cInfo.char, 0, 0)
          }
          ctx.fillText(cInfo.char, 0, 0)
          ctx.setTransform(1, 0, 0, 1, 0, 0)
          charY += cInfo.height
        }
        lineX -= lineWidth
      }

      [ctx.textAlign, ctx.textBaseline] = [oldAlign, oldBaseLine]
    }

    // 需要旋转的Unicode码范围，基本上是CJK文字
    const NO_ROTATION_RANGE = [
      [0x2E80, 0x2FEF],
      [0x3040, 0x9FFF],
      [0xAC00, 0xD7FF],
      [0xF900, 0xFAFF],
      [0x1D300, 0x1D35F],
      [0x20000, 0x2FA1F],
      [0x00b7, 0x00b7],  // 标点符号
      [0x00d7, 0x00d7],
      [0x2014, 0x2014],
      [0x2018, 0x2019],
      [0x201c, 0x201d],
      [0x2026, 0x2026],
      [0x3001, 0x3002],
      [0x300a, 0x300b],
      [0x300e, 0x300f],
      [0x3010, 0x3011],
      [0xff01, 0xff01],
      [0xff08, 0xff09],
      [0xff0c, 0xff0c],
      [0xff1a, 0xff1b],
      [0xff1f, 0xff1f]
    ]


    function needsRotation(char) {
      let codePoint = char.codePointAt(0)
      console.log(char+codePoint.toString(16))
      for (let [lowerBound, upperBound] of NO_ROTATION_RANGE) {
        if (lowerBound <= codePoint && codePoint <= upperBound) {
          return false
        }
      }
      return true
    }
  </script>

</head>

<body>
  <div>
    <!-- <p style="font-family: 'newtext';">已生成{{people_number}}张贺卡</p> -->
  </div>
  <div class="main" id="main">

    <!-- <img id="celebrateCard" src="" alt="" ></img> -->
    <!-- <canvas id='canvas'></canvas> -->
    <img class="final-img" id="celebrateCardImage" src="" alt=""></img>

  </div>
  <div class="info" id="saveGuide">
    <p style="color: black;font-size: 1.5rem;font-weight: bold;margin: 0rem 0 0rem">长按图片可以保存哦</p>
  </div>
</body>


</html>